//
//  JZHDateViewController.m
//  极致荟
//
//  Created by hetao on 14-5-24.
//  Copyright (c) 2014年 mac. All rights reserved.
//

#import "JZHDateViewController.h"
#import "UIButton+Date.h"
#import "JZHLisViewController.h"
@interface JZHDateViewController ()
@property (weak, nonatomic) IBOutlet UIView *datebutview;
@property (weak, nonatomic) IBOutlet UIView *dateMainView;

@end

@implementation JZHDateViewController
NSDateComponents *comps;
NSUInteger unitFlags;
NSCalendar *calendar;

NSMutableArray *datearr;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initViewController:(JZHActivityViewController *)contr
{
    self=[[JZHDateViewController alloc]init];
    self.con=contr;
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    datearr =[[NSMutableArray alloc]init];
    calendar=[NSCalendar currentCalendar];
     unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit |NSCalendarUnitMonth | NSDayCalendarUnit |NSHourCalendarUnit |NSMinuteCalendarUnit |NSWeekdayCalendarUnit|NSWeekOfMonthCalendarUnit;
    
    comps = [calendar components:unitFlags fromDate:[NSDate date]];
    [self.dateMainView.layer setCornerRadius:5.0];
    [self.dateMainView.layer setBorderWidth:1.0];
    [self.dateMainView.layer setBorderColor:[[UIColor grayColor] CGColor]];
    [self LoadDateBut];
    
    //设置左侧按钮
    self.navigationItem.title=@"日期";
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 12, 20)];
    [leftButton addTarget:self action:@selector(leftDrawerButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButton;
    if(OSVersionIsAtLeastiOS7>=7.0)
    {
        self.automaticallyAdjustsScrollViewInsets=NO;
    }
    
}

- (void)leftDrawerButtonPress:(UIButton*)but
{
    [UINavigationController Pop:self];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

///设置月份日期列表按钮
- (void)LoadDateBut
{
    [datearr removeAllObjects];
    //移除所有日期按钮
   for(UIView *view in self.datebutview.subviews)
   {
       [view removeFromSuperview];
   }
    NSLog(@"%@",comps);
    [self setdatetlet];
    
    //把当前月份日期设为1号
    [comps setDay:1];
    comps = [calendar components:unitFlags fromDate:[calendar dateFromComponents:comps]];
    // week 获取当前月份1号为星期几：0=星期天，1=星期1.......
    int week=[comps weekday]-1;
   
    NSRange range = [[NSCalendar currentCalendar] rangeOfUnit: NSCalendarUnitDay inUnit:NSCalendarUnitMonth  forDate:[comps date]];
    //当前月份的天数
    int days=range.length;
    
    if(week!=0)//判断当前月份第一天是否为星期一，如果不是，则填充上月份末尾天数
    {
        [comps setMonth:comps.month-1];
        
        //NSDateComponents似乎是数据模型，要重新通过NSCalendar构造才会改变里面的值
         comps = [calendar components:unitFlags fromDate:[calendar dateFromComponents:comps]];
     
        
        NSRange range = [calendar rangeOfUnit: NSCalendarUnitDay inUnit:NSCalendarUnitMonth  forDate:[calendar dateFromComponents:comps]];
       
        for(int i=0;i<week;i++)
        {
            UIButton *datebut=[[UIButton alloc]initWithFrame:CGRectMake(i*40, 0, 40, 40)];
            [datebut setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [datebut setTitle:[NSString stringWithFormat:@"%d",range.length-(week-i)+1] forState:UIControlStateNormal];
            
            [datebut setFont:[UIFont systemFontOfSize:14.0]];
            [self.datebutview addSubview:datebut];
        }
        [comps setMonth:comps.month+1];
        comps = [calendar components:unitFlags fromDate:[calendar dateFromComponents:comps]];
    }
    int tite=1;
    for (int i=0; i<6; i++)
    {
        for (week; week<7; week++)
        {
            NSDateFormatter *form=[[NSDateFormatter alloc]init];
            [form setDateFormat:@"yyyy-MM-dd"];
            NSString *date1=[form stringFromDate:[NSDate date]];
            [form setDateFormat:@"yyyy-MM-"];
            NSString *date2=[[form stringFromDate:[calendar dateFromComponents:comps]] stringByAppendingString:[NSString stringWithFormat:@"%d",tite]];
            
            UIButton *datebut=[[UIButton alloc]initWithFrame:CGRectMake(week*40, i*40, 40, 40)];
            [datebut setTitle:[NSString stringWithFormat:@"%d",tite] forState:UIControlStateNormal];
            [datebut setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            [datebut setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [datebut setBackgroundImage:[UIImage imageNamed:@"date蓝色点击按钮"] forState:UIControlStateSelected];
            [datebut setBackgroundImage:nil forState:UIControlStateNormal];
            [datearr addObject:date2];
            [datebut setTag:200+tite];
            if([date1 isEqualToString:date2])
            {
                datebut.selected=YES;
            }
            [self.datebutview addSubview:datebut];
            [datebut addTarget:self action:@selector(butselect:) forControlEvents:UIControlEventTouchUpInside];
            [datebut setFont:[UIFont systemFontOfSize:14.0]];
            //判断是否为当前月份的最后一天
            if(tite>=days)
            {
                if(week!=6)//如果当前月份最后一天后面还有空出来的位置，添加下个月的开始几天
                {
                    
                    for(int k=week+1;k<7;k++)
                    {
                        UIButton *datebut=[[UIButton alloc]initWithFrame:CGRectMake(k*40, i*40, 40, 40)];
                        [datebut setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                        [datebut setTitle:[NSString stringWithFormat:@"%d",k-week] forState:UIControlStateNormal];
                        [datebut setFont:[UIFont systemFontOfSize:14.0]];
                        [self.datebutview addSubview:datebut];
                    }
                    ;
                }
                //当前月份的天数只有5行的时候调节界面高度
                if(i!=5)
                {
                    [UIView animateWithDuration:0.0 animations:^{
                        [self.dateMainView setFrame:CGRectMake(self.dateMainView.frame.origin.x, self.dateMainView.frame.origin.y, self.dateMainView.frame.size.width, 314-40)];
                    }];
                }else
                {
                    [UIView animateWithDuration:0.0 animations:^{
                        [self.dateMainView setFrame:CGRectMake(self.dateMainView.frame.origin.x, self.dateMainView.frame.origin.y, self.dateMainView.frame.size.width, 314)];
                    }];
                }
                
                return;
            }
            tite++;
        }
        week=0;
    }
}

- (void)butselect:(UIButton *)but
{
    for(UIButton *datebut in self.datebutview.subviews)
    {
        datebut.selected=NO;
    }
   
    but.selected=YES;
    [self.con hudatestr:[datearr objectAtIndex:but.tag-201]];
    [UINavigationController Pop:self];
}

//设置显示年月内容
- (void)setdatetlet
{
    [self.datetitle setText:[NSString stringWithFormat:@"%@,%d",[self monthEnglish:comps.month],comps.year]];
}

//
- (NSString *)monthEnglish:(int)month
{
    switch (month) {
        case 1:
            return @"January";
            break;
         case 2:return @"February";
            break;
        case 3:return @"March";
            break;
        case 4:return @"April";
            break;
        case 5:return @"May";
            break;
        case 6:return @"June";
            break;
        case 7:return @"July";
            break;
        case 8:return @"August";
            break;
        case 9:return @"September";
            break;
        case 10:return @"October";
            break;
        case 11:return @"November";
            break;
        default:return @"December";
            break;
    }
}
- (IBAction)minus:(id)sender {
    [comps setMonth:comps.month-1];
    [self LoadDateBut];
}
- (IBAction)add:(id)sender {
    [comps setMonth:comps.month+1];
    [self LoadDateBut];
}
@end
